package com.ajhlp.app.phoneDetailQuery.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.log4j.Logger;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.stereotype.Service;

import com.ajhlp.app.phoneDetailQuery.model.ConfigurationNameEnum;
import com.ajhlp.app.phoneDetailQuery.model.JsonResponse;
import com.ajhlp.app.phoneDetailQuery.model.PhoneNumDetail;
@Service
public class HttpPhoneNumDetailServiceImpl extends
		AbstractPhoneNumDetailService {
	private Logger log = Logger.getLogger(getClass());
	

	@Override
	protected String getQueryResult(String phoneNum) {
		// TODO Auto-generated method stub
		HttpClient client = new DefaultHttpClient();

		HttpGet get = new HttpGet(
				IConfigModifyService.configProperties.get(ConfigurationNameEnum.QUERY_URL.getName()).replaceAll("\\{phonenum\\}", phoneNum));
		
		BufferedReader br = null;

		try {
			HttpResponse response = client.execute(get);

			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				String encode = "UTF-8";
				if(response.getEntity().getContentEncoding()!=null){
					encode = response.getEntity().getContentEncoding().getValue();
				}
				
				String tmp = "";
				
				StringBuffer buffer = new StringBuffer();
				
				br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), encode));
				
				while((tmp = br.readLine()) != null){
					buffer.append(tmp);
				}
				
				log.debug(buffer);
				
				return buffer.toString();
				
			}else{
				log.debug(response.getStatusLine().getStatusCode());
				return null;
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			log.error("http请求失败", e);
			return null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			log.error("IO错误", e);
			return null;
		} finally {
			if(br != null){
				try {
					br.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	protected PhoneNumDetail parseQueryResult(String result) {
		// TODO Auto-generated method stub
		if(result == null || "".equals(result.trim())){
			return null;
		}
		
		ObjectMapper objectMapper = new ObjectMapper();
		
		try {
			JsonResponse jsonResponse = objectMapper.readValue(result.toLowerCase(), JsonResponse.class);
			
			return new PhoneNumDetail(jsonResponse.getMobile(), jsonResponse.getAreacode(), jsonResponse.getProvince()+jsonResponse.getCity());
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("json转换失败", e);
			return null;
		} 
	}

}
